package com.lkj;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.lkj.controller.BaseController;
import org.reflections.Reflections;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class HandleImplement implements InvocationHandler {


    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        String name = method.getName();
        System.out.println(name);
        for (int i = 0; i < args.length; i++) {
            System.out.println(args[i]);

        }

        Reflections reflections = new Reflections("com.lkj");
        Set<Class<? extends BaseController>> subTypesOf = reflections.getSubTypesOf(BaseController.class);

        for (Class<? extends BaseController> aClass : subTypesOf) {
            String aClassName = aClass.getAnnotation(MapperRequest.class).value();
            Method[] methods = aClass.getMethods();
            System.out.println(methods.length);
            for (Method method1 : methods) {

                MapperRequest annotation = method1.getAnnotation(MapperRequest.class);
                if (annotation != null) {
                    System.out.println("value:"+annotation.value());
                    String annotationName = aClassName + annotation.value();
                    System.out.println(annotationName);


                    if (annotationName.equals(args[0])){

                        int parameterCount = method1.getParameterCount();
                        if (parameterCount != 1){
                            throw new Exception("控制器参数错误");
                        }
                        System.out.println("parameterCount:"+parameterCount);


                        Class<?> parameterType = method1.getParameterTypes()[0];
                        String name1 = parameterType.getName();
                        System.out.println("className:"+name1);

                        Object bean = null;

                        bean = JSONUtil.toBean((String) args[1], parameterType, true);

                        String result =(String) method1.invoke(aClass.newInstance(),bean);
                        System.out.println("result:"+result  );
                        return result;
                    }
                }

            }
        }

        return null;
    }


}
